package com.oriole.admin.config.websocket;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oriole.admin.config.thread.AsyncManager;
import com.oriole.admin.utils.SystemMonitorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/31 22:45
 * description:
 */
@Component
@ServerEndpoint(value = "/websocket/monitor", configurator = OrioleEndpointConfigure.class)
public class MonitorServer {

    private static final Logger log = LoggerFactory.getLogger(MonitorServer.class);

    /**
     * 连接集合
     */
    private static final Map<String, Session> SESSION_MAP = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        //添加到集合中
        SESSION_MAP.put(session.getId(), session);

        //获取系统监控信息
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                log.info("MonitorWSServer 任务开始");
                ObjectMapper mapper = new ObjectMapper();
                //当属性的值为空（null或者""）时，不进行序列化，可以减少数据传输
                mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
                //设置日期格式
                mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                while (SESSION_MAP.get(session.getId()) != null) {
                    try {
                        //获取系统监控信息 发送
                        send(session, mapper.writeValueAsString(SystemMonitorUtil.getSysMonitor()));
                        //休眠一秒
                        Thread.sleep(5000);
                    } catch (Exception e) {
                        //输出到日志文件中
                        log.error("MonitorWSServer 任务异常");
                    }
                }
                log.info("MonitorWSServer 任务结束");
            }
        };

        AsyncManager.asyncManager().execute(timerTask);

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        //从集合中删除
        SESSION_MAP.remove(session.getId());
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        //输出到日志文件中
        log.info("发生错误时调用");
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务器接收到客户端消息时调用的方法");
    }

    /**
     * 封装一个send方法，发送消息到前端
     */
    private void send(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.info("封装一个send方法，发送消息到前端");
        }
    }
}
